package usersFriendsDao

import (
	"chart.zozoo.net/app/models"
	"chart.zozoo.net/core/mysql"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

type Friend struct {
	Uuid       string `json:"uuid"`
	Notes      string `json:"notes"`
	PerMission int    `json:"permission"`
	Referer    string `json:"referer"`
	Username   string `json:"username"`
	Headimgurl string `json:"headimgurl"`
	Nickname   string `json:"nickname"`
	City       string `json:"city"`
	Profile    string `json:"profile"`
}

// List 获取好友列表
func List(uid int) (list []*Friend, err error) {
	list = make([]*Friend, 0)

	//数据库查询
	userTable := new(models.Users).TableName()
	userFriendsTable := new(models.UserFriends).TableName()

	field := []string{
		userTable + ".uuid",
		userTable + ".username",
		userTable + ".headimgurl",
		userTable + ".nickname",
		userTable + ".city",
		userTable + ".profile",
		userFriendsTable + ".notes",
		userFriendsTable + ".permission",
		userFriendsTable + ".referer",
	}
	res := mysql.MysqlClient.Model(models.UserFriends{}).
		Select(field).
		Joins(fmt.Sprintf("left join %s on %s.id = %s.fid", userTable, userTable, userFriendsTable)).
		Where(userFriendsTable+".uid=?", uid).
		Scan(&list)

	//存在错误，且错误不是未获取到数据
	if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
		return nil, err
	}
	return list, nil
}
